//
//  MineView.swift
//  GuMro
//
//  Created by mac on 2019/12/5.
//  Copyright © 2019 cn.gomro.app. All rights reserved.
//

import UIKit

class MineView: BaseView {
    
    //底部菜单
    private let arrBottomMenus:[[String:String]] = [
        [k_title:"客服中心",k_icon:"mine_service"],
        //[k_title:"意见反馈",k_icon:"mine_advice"],
        //[k_title:"地图中心",k_icon:"mine_map"],//暂时隐藏
        [k_title:"我的台账",k_icon:"mine_ledger"],
        [k_title:"清除缓存",k_icon:"mine_clean"],
        [k_title:"关于我们",k_icon:"mine_about"]
    ]
    
    //顶部菜单高度
    private let top_menu_heigh:CGFloat = 142
    
    //组尾高度
    private let section_foot_view_heigh:CGFloat = 10
    
    //列信息
    private let cell_height:CGFloat = 48
    private let cell_identify:String = "cell_identify"
    
    private var viewModel:MineViewModel?
    
    
    //MARK: - override
    override init(ViewModel vm: ViewModelProtocol) {
        self.viewModel = vm as? MineViewModel
        super.init(ViewModel: vm)
    }
    
    override func updateConstraints() {
        super.updateConstraints()
        
        self.listTableView.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.edges.equalTo(self)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setupViews() {
        
        self.backgroundColor = {
            if #available(iOS 13.0, *) {
                let _c = UIColor.init(dynamicProvider: { (traitCollection:UITraitCollection) -> UIColor in
                    if traitCollection.userInterfaceStyle == .dark {
                        return UIColor.systemBackground
                    }
                    return UIColor.init(hexString: "#F0F1F4")!
                })
                return _c
            }
            return UIColor.init(hexString: "#F0F1F4")!
        }()
        
        self.addSubview(self.listTableView)
        
        setNeedsUpdateConstraints()
    }
    
    
    //MARK: - lazy load
    lazy var listTableView:UITableView = {
        let _tb = UITableView.init(frame: CGRect.zero,
                                   style: UITableView.Style.plain)
        _tb.backgroundColor = UIColor.clear
        _tb.isScrollEnabled = true
        
        _tb.showsVerticalScrollIndicator = false
        _tb.showsHorizontalScrollIndicator = false
        
        //适配平板
        _tb.cellLayoutMarginsFollowReadableWidth = false
        
        //分割线
        _tb.separatorStyle = .singleLine
        _tb.separatorColor = K_APP_SPLIT_LINE_COLOR
        
        //行选中
        _tb.allowsSelection = true
        _tb.allowsMultipleSelection = false
        
        //表头、表尾
        _tb.tableHeaderView = UIView.init(frame: .zero)
        _tb.tableFooterView = UIView.init(frame: .zero)
        
        _tb.delegate = self
        _tb.dataSource = self
        
        //防止顶部空白
        if #available(iOS 11.0, *) {
            _tb.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        }
        
        //注册
        _tb.register(UITableViewCell.classForCoder(),
                     forCellReuseIdentifier: cell_identify)
        
        return _tb
    }()
    
    
    lazy var mineHead:MineHead = {
        autoreleasepool {
            let _m = MineHead.init()
            
            _m.showUserDetailsBlock = {[weak self] in
                self?.viewModel?.showUserInfo.sendNext(nil)
            }
            
            _m.gotoLoginBlock = {[weak self] in
                self?.viewModel?.gotoLogin.sendNext(nil)
            }
            
            return _m
        }
    }()
    
    private lazy var sectionFootView:UIView = {
        autoreleasepool {
            let _v = BaseView.createView(rect: CGRect.init(x: 0, y: 0, width: K_APP_WIDTH, height: section_foot_view_heigh),
                                backgroundColor: K_APP_SPLIT_STRIP_COLOR,
                                isRadius: false,
                                cornerRadius: 0)
            return _v
        }
    }()
}


//MARK: - UITableViewDelegate,UITableViewDataSource
extension MineView: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    //MARK:组头、组尾
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        //MARK:用户信息
        if section == 0 {
            return MineHead.mine_head_height
        }
        
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        //MARK:用户信息
        if section == 0 {
            return self.mineHead
        }
        
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return section_foot_view_heigh
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return self.sectionFootView
    }
    
    //MARK:列
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return self.arrBottomMenus.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   
        if indexPath.section == 1 {
            return cell_height
        }
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        autoreleasepool {
            var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cell_identify)
            if cell == nil {
                cell = UITableViewCell.init(style: .default, reuseIdentifier: cell_identify)
            }
            
            cell?.backgroundColor = K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
            
            if self.arrBottomMenus.count > indexPath.row {
                 let dicData = self.arrBottomMenus[indexPath.row]
                           
                 cell?.imageView?.image = YYImage.init(named: dicData[k_icon]!)
                
                 let strText = "\(dicData[k_title] ?? "")"
                 cell?.textLabel?.text = strText
                
                 if strText == "清除缓存" {
                    cell?.accessoryType = .none
                    
                    let right = BaseView.createLable(rect: .init(x: 0, y: (cell_height - 21) * 0.5, width: 60, height: 21),
                                                     text: Utils.shareInstance().getAppCacheSize(),
                                                     textColor: UIColor.init().colorFromHexInt(hex: 0xadadad),
                                                     font: UIFont.systemFont(ofSize: 12))
                    right.layoutMargins = .init(top: 0, left: 0, bottom: 0, right: 5)
                    right.textAlignment = .right
                    cell?.accessoryView = right
                 }
                 else{
                    //右边箭头
                    cell?.accessoryType = .disclosureIndicator
                 }
                 
            }
            
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        defer {
            tableView.deselectRow(at: indexPath, animated: true)
        }
        
        if self.arrBottomMenus.count > indexPath.row {
            let dicData = self.arrBottomMenus[indexPath.row]

            self.viewModel?.cellDidSelect.sendNext(dicData[k_title]!)
        }
    }
    
}
